__author__ = 'shawhen'

from . import what as m_what_platform


def get_meminfo():
    meminfo = {}
    if m_what_platform.running_os["type"] == "linux":
        meminfo_file = open("/proc/meminfo")
        lines = meminfo_file.readlines()
        meminfo_file.close()

        for line in lines:
            if len(line) < 3:
                continue
            name, value_with_kb = line.split(":")
            value_text = value_with_kb.strip().split(" ")[0]
            if name == "MemTotal":
                meminfo["total"] = int(value_text) * 1024
            elif name == "MemFree":
                meminfo["free"] = int(value_text) * 1024
            elif name == "MemAvailable":
                meminfo["available"] = int(value_text) * 1024
            else:
                meminfo[name] = int(value_text) * 1024
        if "available" not in meminfo:
            meminfo["available"] = meminfo["free"]
    elif m_what_platform.running_os["type"] == "windows":
        from ..sysapi.win32 import windows

        memory_status_ex = windows.GlobalMemoryStatusEx()
        if memory_status_ex is None:
            raise ValueError("get memroy status failed,ec: {0}".format(windows.GetLastError()))
        meminfo["total"] = memory_status_ex.ullTotalPhys
        meminfo["free"] = memory_status_ex.ullAvailPhys

        if "available" not in meminfo:
            meminfo["available"] = meminfo["free"]
    else:
        raise NotImplementedError
    return meminfo
